# -*- coding: utf-8 -*-
import json
import re

from flask import request
from flask_restx import Resource, Namespace, fields

from utils.response import ResponseMaker
from app.models.user import User
from app.extentions import db
from utils.jwt import JWTUtil


auth_api = Namespace("auth", description="认证", path="/api/auth")


auth_model = auth_api.model('LoginModel', {
    'account': fields.String(required=True, description='账号'),
    'password': fields.String(required=True, description='密码')
})

register_model = auth_api.model('RegisterModel', {
    'account': fields.String(required=True, description='账号'),
    'password': fields.String(required=True, description='密码'),
    'name': fields.String(required=True, description='用户姓名'),
})


@auth_api.route('/login')
class UserAPI(Resource):
    @auth_api.doc(description='登录', body=auth_model)
    def post(self):
        data = json.loads(request.data)
        account = data.get("account")
        password = data.get("password")

        user = User.query.filter_by(account=account).first()
        if not user:
            return ResponseMaker.user_account_not_found()

        if user.password != password:
            return ResponseMaker.user_password_error()

        # 生成token
        access_token_data = JWTUtil.create_token(user.id)
        access_token = access_token_data.get("access_token")
        token_expires = access_token_data.get("token_expires")

        resp_data = {
            'token': "Bearer " + access_token,
            'account': user.account,
            'uid': user.id,
            'name': user.name
        }

        return ResponseMaker.success(resp_data)


@auth_api.route('/logout')
class UserAPI(Resource):
    @auth_api.doc(description='登出')
    def post(self):
        return ResponseMaker.success()


@auth_api.route('/register')
class UserAPI(Resource):
    @auth_api.doc(description='注册', body=register_model)
    def post(self):
        data = json.loads(request.data)
        account = data.get("account")
        password = data.get("password")
        name = data.get("name")

        user = User.query.filter_by(account=account).first()
        if user:
            return ResponseMaker.user_account_already_exist()

        # 校验account格式
        is_valid = account_regex_check(account)
        if not is_valid:
            return ResponseMaker.account_format_error()

        new_user = User(account=account, password=password, name=name)
        db.session.add(new_user)
        db.session.commit()

        return ResponseMaker.success()


def account_regex_check(account):
    """
    校验account字段的合法性

    校验规则：以手机号码作为账号，正则规则是以1开头的11位数字。
    """
    pattern = re.compile(r"^1[0-9]{10}$")
    is_valid = re.match(pattern, account) is not None
    return is_valid